package com.example.parallelandroid;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.parallelandroid.entity.User;
import com.example.parallelandroid.utils.EncryptUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.mob.MobSDK;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ForgetPasswordActivity extends AppCompatActivity implements View.OnClickListener{
    EventHandler eventHandler;
    EditText edtPhone,edtCode,edtPassword,edtConfirmPassword;
    Button btnSave,btnCode;
    private SharedPreferences sharedPreferences;
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    Timer timer;
    int count = 60;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){
        public void handleMessage(Message msg) {
            int tag = msg.what;
            switch (tag){
                case 1:
                    int arg = msg.arg1;
                    if(arg==1){
                        btnCode.setText("重新获取");
                        count = 60;
                        timer.cancel();
                        btnCode.setEnabled(true);
                    }else{
                        btnCode.setText(count+"");
                    }
                    break;
                case 2:
                    Toast.makeText(ForgetPasswordActivity.this,"获取短信验证码成功",Toast.LENGTH_LONG).show();
                    break;
                case 3:
                    Constant.logger.info("获取短信验证码: 失败");
                    Toast.makeText(ForgetPasswordActivity.this,"获取短信验证码失败",Toast.LENGTH_LONG).show();
                    break;
                case 4:
                    savePassword();
                    Intent intent = new Intent(ForgetPasswordActivity.this,LoginActivity.class);
                    startActivity(intent);
                    finish();
                    break;
                default:
                    break;
            }

        }
    };

    private void savePassword() {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("isRemember",false);
        editor.putBoolean("isAutoLogin",false);
        editor.commit();
        OkHttpClient okHttpClient = new OkHttpClient();
        User user = new User();
        String userName = sharedPreferences.getString("phone","");
        String password = sharedPreferences.getString("confirmPassword","");
        String id = sharedPreferences.getString("userId","");
        user.setUserName(userName);
        user.setPassword(EncryptUtils.encrypt(password));
        user.setUserId(id);
        String json = new Gson().toJson(user);
        RequestBody requestBody = RequestBody.create(JSON,json);
        Constant.logger.info("开始向服务端传输User用于修改密码 userId=" + user.getUserId());
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "user/createUser")
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Constant.logger.warn("向服务端传输User用于修改密码: 失败", e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String json = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    String msg = jsonObject.getString("msg");
                    Constant.logger.info("服务端Response: " + msg);
                } catch (JSONException e) {
                    Constant.logger.warn("解析服务端Response: 失败", e);
                }
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_password);

        sharedPreferences = getSharedPreferences("user",
                MODE_PRIVATE);

        MobSDK.submitPolicyGrantResult(true);

        getView();

        init();

        //密码限制
        edtPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String pwd = edtPassword.getText().toString();
                if(TextUtils.isEmpty(pwd)&&"".equals(pwd)){
                    edtPassword.setError("请输入密码");
                }else {
                    if(pwd.length()>=6&&pwd.length()<=12){

                    }else {
                        edtPassword.setError("请输入8到15位密码，包含大小写字母、数字、特殊字符");

                    }
                }
            }
        });
    }

    private void getView() {
        edtPhone = findViewById(R.id.edt_phone);
        edtCode = findViewById(R.id.edt_code);
        edtPassword = findViewById(R.id.edt_password);
        edtConfirmPassword = findViewById(R.id.edt_confirm_password);
        btnSave = findViewById(R.id.btn_save);
        btnSave.setOnClickListener(this::onClick);
        btnCode = findViewById(R.id.btn_code);
        btnCode .setOnClickListener(this::onClick);
    }

    private void init(){
        eventHandler = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
// TODO 此处为子线程！不可直接处理UI线程！处理后续操作需传到主线程中操作！
                if (result == SMSSDK.RESULT_COMPLETE) {
//成功回调
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        Message message = new Message();
                        message.what = 4;
                        handler.sendMessage(message);
//提交短信、语音验证码成功
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        Message message = new Message();
                        message.what = 2;
                        handler.sendMessage(message);
                    } else if (event == SMSSDK.EVENT_GET_VOICE_VERIFICATION_CODE) {
//获取语音验证码成功
                        Message message = new Message();
                        message.what = 2;
                        handler.sendMessage(message);
                    }
                } else if (result == SMSSDK.RESULT_ERROR) {
//失败回调
                    Message message = new Message();
                    message.what = 3;
                    handler.sendMessage(message);
                } else {
//其他失败回调
                    ((Throwable) data).printStackTrace();
                }
            }
        };
        SMSSDK.registerEventHandler(eventHandler); //注册短信回调
    }

    @Override
    public void onClick(View v) {
        String phone = "";
        String code = "";
        String password = "";
        String confirmPassword = "";
        int id = v.getId();
        switch (id) {
            case R.id.btn_code:
                phone = edtPhone.getText().toString().trim();
                if (!TextUtils.isEmpty(phone)) {
                    //倒计时
                    CountdownStart();
                    getVerificationCode("86", phone);
                } else {
                    Toast.makeText(this, "请输入手机号码", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.btn_save:
                SharedPreferences.Editor editor = sharedPreferences.edit();
                phone = edtPhone.getText().toString().trim();
                code = edtCode.getText().toString().trim();
                password = edtPassword.getText().toString().trim();
                confirmPassword = edtConfirmPassword.getText().toString().trim();
                String pw = sharedPreferences.getString("password","");
                if (TextUtils.isEmpty(phone)) {
                    Toast.makeText(this, "请输入手机号码", Toast.LENGTH_LONG).show();
                } else if (TextUtils.isEmpty(code)) {
                    Toast.makeText(this, "请输入验证码", Toast.LENGTH_LONG).show();
                } else if (TextUtils.isEmpty(password)){
                    Toast.makeText(this, "请输入密码", Toast.LENGTH_LONG).show();
                }else if (TextUtils.isEmpty(confirmPassword)){
                    Toast.makeText(this, "请再次输入确认密码", Toast.LENGTH_LONG).show();
                }else if(!password.equals(confirmPassword)){
                    Toast.makeText(this, "两次密码输入不相同", Toast.LENGTH_LONG).show();
                } else if(pw.equals(confirmPassword)){
                    Toast.makeText(this, "你所输入密码与原密码相同", Toast.LENGTH_LONG).show();
                } else if(!checkPassword(confirmPassword)){
                    Toast.makeText(this, "请输入8到15位密码，包含大小写字母、数字、特殊字符", Toast.LENGTH_LONG).show();
                }else {
                    editor.putString("password",confirmPassword);
                    editor.commit();
                    SMSSDK.submitVerificationCode("86", phone, code);
                    finish();
                }
                break;
        }
    }

    private boolean checkPassword(String confirmPassword) {
        boolean capitalFlag = false;
        boolean lowerCaseFlag = false;
        boolean numberFlag = false;
        boolean numLength = false;
        boolean res = false;
        // 获取用户输入的新密码
        String newPwd = confirmPassword;
        for (int i=0; i<newPwd.length(); i++) {
            Character ch = newPwd.charAt(i);
            if( Character.isDigit(ch)) {
                numberFlag = true;
            } else if (Character.isUpperCase(ch)) {
                capitalFlag = true;
            } else if (Character.isLowerCase(ch)) {
                lowerCaseFlag = true;
            }
        }
        if (newPwd.length() >= 6 && newPwd.length() <= 16){
            numLength = true;
        }
        if(numberFlag && capitalFlag && lowerCaseFlag && numLength) {
            res = true;
        }
        return res;
    }

    public static void getVerificationCode(String country, String phone){
        //获取短信验证码
        SMSSDK.getVerificationCode(country,phone);
    }

    //倒计时函数
    private void CountdownStart(){
        btnCode.setEnabled(false);
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 1;
                message.arg1 = count;
                if(count!=0){
                    count--;
                }else {
                    return;
                }
                handler.sendMessage(message);
            }
        }, 1000,1000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
// 使用完EventHandler需注销，否则可能出现内存泄漏
        SMSSDK.unregisterEventHandler(eventHandler);
    }
}